/*
 * @Author: XiaoHe
 */
/*
 * @Author: XiaoHe
 */
package cn.he4966.xiaohepdf;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.HashMap;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;


 
@RestController
public class PdfController {

    //http://127.0.0.1:9988/pdf_to_images?in_path=/Users/wk/Desktop/jcgcw.pdf&out_path=/Users/wk/Desktop/jcgcw2/

    @GetMapping("/pdf_to_images")
    public String pdf_to_images(@RequestParam("in_path") String inPath,
    @RequestParam(name = "out_path", required = true) String outPath,
    @RequestParam(name = "dpi", required = false ,defaultValue = "300") Integer dpi,
    @RequestParam(name = "bug", required = false ,defaultValue = "false") String bug) {
        System.out.println("in_path:" + inPath);
        System.out.println("out_path:" + outPath);
        
        HashMap<String, Object> data = new HashMap<>();
        data.put("code", 0);
    
        // 判断文件是否存在
        if (!FileUtil.exist(inPath)) {
            data.put("msg", "文件不存在");
            System.out.println("文件不存在");
            return JSONUtil.toJsonStr(data);
        }
       
        // 判断文件是否是pdf
        if (!inPath.endsWith(".pdf")) {
            data.put("msg", "不是pdf文件");
            System.out.println("不是pdf文件");
            return JSONUtil.toJsonStr(data);
        }

        //判断输出目录是否为空
        if (outPath == null || outPath.equals("")) {
            data.put("msg", "输出目录为空");
            System.out.println("输出目录为空");
            return JSONUtil.toJsonStr(data);
        }
        

        PdfToImageService pdfToImageService = new PdfToImageService();
        try {
            data.put("images",  pdfToImageService.convertPdfToImages(inPath,outPath,dpi,bug));
            data.put("out_path", outPath);
            data.put("code", 1);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("pdf转图片失败");
            data.put("code", 0);
        }
        
        //用hutool 转成json返回
        return JSONUtil.toJsonStr(data);

        // return new ObjectMapper().writeValueAsString(data);
        // return data.toString();
        // return "Hello World xiaohe";
    
    }
}
